from image_utils import logging # 从image_utils.py中导入logging对象
import numpy as np


def adjust_brightness(image, factor):
    """
    调整图像亮度
    :param image: 输入图像，numpy数组
    :param factor: 亮度调节因子(0.0-2.0)
    :return: 调整后的图像
    """
    try:
        logging.info(f"开始调整亮度，调节因子: {factor}")
        
        # 备份原始数据类型
        original_dtype = image.dtype
        
        # 转换为float32处理
        if image.dtype != np.float32:
            image = image.astype(np.float32)
            
        # 处理RGB图像
        if len(image.shape) == 3:
            adjusted = np.clip(image * factor, 0, 255)
        # 处理灰度图像
        elif len(image.shape) == 2:
            adjusted = np.clip(image * factor, 0, 255)
        else:
            raise ValueError("Unsupported image shape")
            
        # 转换回原始数据类型
        if original_dtype == np.uint8:
            adjusted = adjusted.astype(np.uint8)
        elif original_dtype == np.float32:
            adjusted = adjusted.astype(np.float32)
        elif original_dtype == np.float64:
            adjusted = adjusted.astype(np.float64)
            
        logging.info("亮度调整成功")
        return adjusted
    except Exception as e:
        logging.error(f"亮度调整失败: {str(e)}")
        raise ValueError(f"Error occurred while adjusting brightness: {e}")


def crop_image(image, crop_region):
    """
    裁剪图像
    :param image: 输入图像，PIL.Image对象
    :param crop_region: 裁剪区域,格式为(上,下,左,右)
    :return: 裁剪后的图像
    """
    try:
        logging.info(f"开始裁剪图像，裁剪区域,{crop_region}")
        
        # 从crop_region中提取上、下、左、右的坐标
        top, bottom, left, right = crop_region
        
        # 使用切片操作裁剪图像
        cropped_image = image[top:bottom, left:right]
        
        logging.info(f"图像裁剪成功，裁剪后尺寸: {cropped_image.shape}")
        return cropped_image
    except Exception as e:
        raise ValueError(f"Error occurred while cropping image: {e}")


def apply_global_threshold(image, threshold):
    """
    应用全局阈值处理
    :param image: 输入图像，numpy数组
    :param threshold: 阈值 (0-255)
    :return: 二值化后的图像
    """
    try:
        logging.info(f"开始应用全局阈值处理，阈值: {threshold}")
        
        # 转换为灰度图像
        if len(image.shape) == 3:
            image = np.mean(image, axis=2)
        
        # 应用阈值
        binary_image = np.where(image > threshold, 255, 0)
        
        logging.info("全局阈值处理成功")
        return binary_image.astype(np.uint8)
    except Exception as e:
        logging.error(f"全局阈值处理失败: {str(e)}")
        raise ValueError(f"Error occurred while applying global threshold: {e}")